package com.meraklisina.latexeditor;

import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;
import java.awt.TrayIcon.MessageType;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.BadLocationException;



public class AutoComplete implements ListSelectionListener {
	JList nameList;
    private DefaultListModel listModel;
    private int keyboardAdjusting = 1;
    private int iteratorPos = 1;
    JScrollPane listScrollPane;
    Frame completeMenu;
    JTextPane jtp;
    Language lang = new Language();
    
    private String syntaxWords[] = new TextEditors().syntaxWords;
	
	public AutoComplete(Frame a_completeMenu)
	{
		lang.LoadLanguage(BlueLatexEditor._language);
		
		completeMenu = a_completeMenu;
		
        completeMenu.setSize(new Dimension(170, 100));
        completeMenu.setAlwaysOnTop(true);
        completeMenu.setResizable(false);
        
        nameList = new JList();
        nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        nameList.addListSelectionListener(this);
        
        nameList.addFocusListener(new java.awt.event.FocusListener() {
			public void focusGained(FocusEvent arg0) {
				
			}

			public void focusLost(FocusEvent arg0) {
				completeMenu.setVisible(false);
			}
        });
        
        nameList.addKeyListener(new java.awt.event.KeyListener() {
			public void keyPressed(KeyEvent arg0) {
				String key = KeyEvent.getKeyText(arg0.getKeyCode());
				
				if(key.equalsIgnoreCase("Enter"))
				{
					try{
						insertChars();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					
					completeMenu.setVisible(false);
				}
				else if(key.equalsIgnoreCase("Escape"))
				{
					completeMenu.setVisible(false);
				}
			}

			public void keyReleased(KeyEvent arg0) {
				
			}

			public void keyTyped(KeyEvent arg0) {
				
			}
        });
        
        listScrollPane = new JScrollPane(nameList);
        
        completeMenu.add(listScrollPane, BorderLayout.CENTER);
	}
	
	public void setTextPane(JTextPane a_jtp)
	{
		jtp = a_jtp;
	}
	
	public void actionPerformed(ActionEvent e) {
		System.out.println("action performed"); 
	}
	
	public void PopMenu()
	{
        Point pnt1 = jtp.getLocationOnScreen();
		Point pnt2 = jtp.getCaret().getMagicCaretPosition();
		
        completeMenu.setLocation(pnt1.x + pnt2.x + 3, pnt1.y + pnt2.y + 10);
        
        if(AddWordsToList(GetCharsToComplete()) == 0)
        	completeMenu.setVisible(true);
	}

	
	public void valueChanged(ListSelectionEvent arg0) {
		if(arg0.getValueIsAdjusting() == false)
		{
			if(keyboardAdjusting == 0)
			{
				completeMenu.setVisible(false);
				//System.out.println(nameList.getSelectedValue());

				insertChars();
			}
			
			keyboardAdjusting = 1;
		}
		else
		{
			keyboardAdjusting = 0;
		}
	}
	
	private void insertChars()
	{
		if(nameList.getSelectedValue().toString().equals(lang.NoProposals) == true)
			return;
		
		try{
			jtp.getDocument().insertString(jtp.getCaretPosition(), nameList.getSelectedValue().toString().substring(iteratorPos), null);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private String GetCharsToComplete()
	{
		int caretPos = jtp.getCaretPosition();
		int startPos = 0;
		String charsToComplete = "";
		
		try{
			for(iteratorPos = 1; ; iteratorPos++)
			{
				startPos = caretPos - iteratorPos;
				if(startPos < 0)
					startPos = 0;
				
				charsToComplete = jtp.getText(startPos, iteratorPos);
				//System.out.println(charsToComplete);
				if( (charsToComplete.contains(" ") || charsToComplete.contains("\t") || charsToComplete.contains("\n")) )
				{
					iteratorPos -= 1;
					charsToComplete = jtp.getText(caretPos - iteratorPos, iteratorPos);	
					break;
				}
				
				if(startPos == 0)
					break;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			iteratorPos = 0;
		}
		
		return charsToComplete;
	}
	
	private int AddWordsToList(String charsToMatch)
	{
		int i = 0;
		
		//System.out.println(iteratorPos);
		
		if(iteratorPos < 2)
			return -1;
		
        listModel = new DefaultListModel();
        
        for(; i < syntaxWords.length; i++)
		{
			if(syntaxWords[i].startsWith(charsToMatch) /*contains(charsToMatch)*/)
				listModel.addElement(syntaxWords[i]);
		}
        
        if (listModel.getSize() <= 0)
        	listModel.addElement(lang.NoProposals);
        
        nameList.setModel(listModel);
        //nameList.setSelectedIndex(0);
        
        return 0;
	}
}
